import csv


# 导出csv文件
def exportCsvForWeb(result, column_names):
    from io import StringIO # python 必须使用StringIO,python2使用 ByteIo

    file = StringIO()
    writer = csv.writer(file, dialect='excel')
    # 列名
    if column_names is not None:
        writer.writerow(column_names)
    # 行数据
    row_data_list = build_row_data_list(result, column_names)
    for row_data in row_data_list:
        writer.writerow(row_data)

    return file.getvalue()


# 导出csv文件到本地
def exportCsvForLocal(file_path, result, columnNames):
    with open(file_path, 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file, dialect='excel')

        if columnNames is not None:
            writer.writerow(columnNames)

        row_data_list = build_row_data_list(result, columnNames)
        for row_data in row_data_list:
            writer.writerow(row_data)

# 导出csv文件到本地
def exportCsvLocalByDataList(file_path, row_data_list, columnNames):
    with open(file_path, 'w', newline='', encoding='utf-8') as csv_file:
        writer = csv.writer(csv_file, dialect='excel')

        if columnNames is not None:
            writer.writerow(columnNames)

        for row_data in row_data_list:
            writer.writerow(row_data)

# 构造行数据
def build_row_data_list(result, columnNames):
    import datetime
    import pandas

    row_data_list = []
    for i in range(result[columnNames[0]].size):
        row_data = []
        for name in columnNames:
            value = result[name][i]
            if not value:
                row_data.append(value)
            elif pandas.isna(value):
                row_data.append('')
            elif isinstance(value, bytes):
                row_data.append(str(value, encoding="utf-8"))
            elif isinstance(value, datetime.date):
                row_data.append(value.strftime('%Y-%m-%d %H:%M:%S'))
            else:
                row_data.append(eval(repr(value)))

        row_data_list.append(row_data)

    return row_data_list
